# _*_ coding: utf-8 _*_
import re
import json
from MatchModule import *
from Data.Table import Table,tableStruct,Data,Field
'''

处理数据库命令，将数据实现和内存的互通
'''
class Engine:
    data_, tableStruct_, field_= None, None, None
    field = []
    tablestrct_ = []
    Last_id=0
    def __init__(self):
        self.TIPS=""
    def CreateTable(self,sql):
        '''
        主要的建表函数，返回tableStruct对象
        :param sql:
        :return:
        '''
        if self.is_Create(sql):
            table_name=self.get_Tablename(sql)
            table_primary_key = self.get_PrimaryKey(sql).keys()
            table_foreign_key=self.get_ForeignKey(sql)
            table_fields=self.build_Fields(sql)
            tablestruct=tableStruct(table_name, table_fields, table_primary_key, table_foreign_key)
            return tablestruct
    def InsertTable(self,sql):
        pass
    def SelectTable(self,sql):
        pass
    def AddToTable(self,sql):
        pass
    def class_to_dict(self,tableStruct_):
        is_list=tableStruct_.__class__==[].__class__
        is_set=tableStruct_.__class__==set().__class__
        to_dic=[]
        if is_list or is_set:
            for i in tableStruct_:
                dict={}
                dict.update(i.__dict__)
                to_dic.append(dict)
            return to_dic
        else:
            dict={}
            dict.update(tableStruct_.__dict__)
            return dict
    def is_Create(self,sql):
        '''
        判断是否为create语句，返回bool变量
        :param sql:
        :return:
        '''
        is_create = re.match(pattern_create, sql, re.I)
        if is_create == None:
            return False
        else:
            return True
    def is_Alter(self, sql):
        is_alter = re.match(pattern_alter, sql, re.I)
        if is_alter == None:
            return False
        else:
            return True
    def get_Tablename(self, sql):
        tableName_ = re.match(pattern_create, sql, re.I).group(1)
        return tableName_
    def get_Field(self,sql):
        '''
        返回字段名称，返回一个字段名称数组
        :param sql:
        :return:
        '''
        Fieldpart=re.match(pattern_create, sql, re.I).group(2)
        Fieldname=[]
        Fields=Fieldpart.split(',')
        for i in Fields:
            Fieldname.append(i.split()[0])
        return Fieldname
    def get_Types(self,sql):
        '''
        返回字段类型，返回一个字段类型数组
        :param sql:
        :return:
        '''
        Fieldpart = re.match(pattern_create, sql, re.I).group(2)
        Fieldname = []
        Fields = Fieldpart.split(',')
        for i in Fields:
            Fieldname.append(i.split()[1])
        return Fieldname
    def get_Binds(self,sql):
        '''
        获取语句中的字段约束对象，返回Binds_ 类型dict
        :param sql:
        :return:
        '''
        Fieldpart = re.match(pattern_create, sql, re.I).group(2)
        Fields = Fieldpart.split(',')
        Binds_={}
        for i in Fields:
            if re.search("not null", i, re.I):
                Binds_[i.split()[0]]=re.search("not null", i, re.I).group()
            elif re.search("null", i, re.I):
                Binds_[i.split()[0]]=re.search("null", i, re.I).group()
        return Binds_
    def get_PrimaryKey(self,sql):
        '''
        获取语句的PrimaryKey，返回dict类型
        :param sql:
        :return:
        '''
        Fieldpart = re.match(pattern_create, sql, re.I).group(2)
        Fields = Fieldpart.split(',')
        PrimaryKeys_ = {}
        for i in Fields:
            if re.search("primary\s*key", i, re.I):
                PrimaryKeys_[i.split()[0]] = re.search("primary\s*key", i, re.I).group()
        return PrimaryKeys_
    def get_ForeignKey(self,sql):
        '''
        获取语句的ForeignKey，返回dict类型
        :param sql:
        :return:
        '''
        Fieldpart = re.match(pattern_create, sql, re.I).group(2)
        Fields = Fieldpart.split(',')
        ForeignKeys_ = {}
        for i in Fields:
            if re.search("foreign\s*key", i, re.I):
                ForeignKeys_[i.split()[0]] = re.search("primary\s*key", i, re.I).group()
        return ForeignKeys_
    def dict_to_class(self, obj, dataType):
        '''
        字典转字符串，适用数组和单个对象
        :param obj:
        :return:
        '''
        is_list=obj.__class__ == [].__class__
        to_class=[]
        if is_list:
            for o in obj:
                dataType.__dict__ = o
                to_class.append(o)
            return to_class
        else:
            dataType.__dict__ = obj
            return dataType
    def build_Fields(self, sql):
        to_fields=[]
        names = self.get_Field(sql)
        types=self.get_Types(sql)
        for i in range(len(names)):
            try:
                bind=self.get_Binds(sql)[names[i]]
            except:
                bind=None
            F = Field(names[i], types[i], bind)
            to_fields.append(F)
        return self.class_to_dict(to_fields)
"""if __name__ == '__main__':
    te = Engine()
    #te.Test()
    sqll = raw_input("sql>")
    '''print te.build_Fields(sqll)
    print te.get_Field(sqll)
    print te.get_Tablename(sqll)
    print te.get_Types(sqll)
    print te.get_Binds(sqll)
    print te.get_PrimaryKey(sqll)'''
    #print te.class_to_dict(te.CreateTable(sqll))
    '''tablestruct = json.load(open("../Data/db.emp", "r"))'''
    '''table = tableStruct(None, None, None, None)'''
    #print type(tablestruct)
    F = Field(None, None, None)
    '''for i in tablestruct:
        table=tableStruct(None,None,None,None)
        table.__dict__ = i
        #print table.name_,table.fields_,table.primaryKey_,table.foreignKey
        F = Field(None,None,None)
        print type(table.fields_)
        for h in table.fields_:
            F.__dict__ = h
            print F.name_,F.size_,F.type_'''
    #tas = te.dict_to_class(tablestruct,table)
    print te.CreateTable(sqll)
    print type(te.CreateTable(sqll))

    s=[]
    json_file = json.load(open("../Data/tb.emp", 'r'))
    for i in json_file:
        s.append(i)
    s.append(te.class_to_dict(te.CreateTable(sqll)))
    json.dump(s, open("../Data/tb.emp", "w"), indent=4)
    #print type(tas)
        #table.__dict__=i
        #f = te.dict_to_class(table.fields_,F)
        #for j in f:
            #F.__dict__=j
            #print F.type_"""